<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <!-- 左侧个人信息卡片 -->
      <el-col :span="16">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <el-button type="primary" @click="handleEdit" v-if="!isEditing"
                >编辑</el-button
              >
            </div>
          </template>

          <!-- 查看模式 -->
          <el-form :model="userInfo" label-width="100px" v-if="!isEditing">
            <el-form-item label="用户名">
              <span>{{ userInfo.username }}</span>
            </el-form-item>
            <el-form-item label="昵称">
              <span>{{ userInfo.nickname }}</span>
            </el-form-item>
            <el-form-item label="邮箱">
              <span>{{ userInfo.email }}</span>
            </el-form-item>
            <el-form-item label="创建时间">
              <span>{{ userInfo.createTime }}</span>
            </el-form-item>
          </el-form>

          <!-- 编辑模式 -->
          <el-form
            v-else
            ref="formRef"
            :model="editForm"
            :rules="rules"
            label-width="100px"
          >
            <el-form-item label="昵称" prop="nickname">
              <el-input
                v-model="editForm.nickname"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSave">保存</el-button>
              <el-button @click="cancelEdit">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 修改密码卡片 -->
        <el-card class="password-card">
          <template #header>
            <div class="card-header">
              <span>修改密码</span>
            </div>
          </template>

          <el-form
            ref="pwdFormRef"
            :model="pwdForm"
            :rules="pwdRules"
            label-width="100px"
          >
            <el-form-item label="原密码" prop="oldPassword">
              <el-input
                v-model="pwdForm.oldPassword"
                type="password"
                show-password
                maxlength="20"
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="pwdForm.newPassword"
                type="password"
                show-password
                maxlength="20"
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="pwdForm.confirmPassword"
                type="password"
                show-password
                maxlength="20"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleChangePwd"
                >修改密码</el-button
              >
              <el-button @click="resetPwdForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧头像卡片 -->
      <el-col :span="8">
        <el-card class="avatar-card">
          <template #header>
            <div class="card-header">
              <span>头像设置</span>
            </div>
          </template>
          <div class="avatar-container">
            <el-avatar
              :size="120"
              :src="userInfo.imgPath"
              @error="handleAvatarError"
            >
              <img
                src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
              />
            </el-avatar>
            <div class="avatar-actions">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="handleAvatarUpload"
              >
                <el-button type="primary">更换头像</el-button>
              </el-upload>
              <p class="upload-tip">支持 jpg、png 格式，大小不超过 2MB</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  getUserInfo,
  updateUserInfo,
  uploadAvatar,
  changePassword,
} from "../apis/user";

const isEditing = ref(false);
const formRef = ref();
const pwdFormRef = ref();

// 用户信息
const userInfo = ref({
  username: "",
  nickname: "",
  email: "",
  createTime: "",
  imgPath: "",
});

// 编辑表单
const editForm = ref({
  nickname: "",
  email: "",
});

// 密码表单
const pwdForm = ref({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 表单校验规则
const rules = {
  nickname: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
};

// 密码校验规则
const pwdRules = {
  oldPassword: [
    { required: true, message: "请输入原密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认新密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== pwdForm.value.newPassword) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error("头像只能是 JPG 或 PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("头像大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 获取用户信息
const fetchUserInfo = async () => {
  const res = await getUserInfo();
  userInfo.value = res.data;
};

// 处理头像上传
const handleAvatarUpload = async (options) => {
  const formData = new FormData();
  formData.append("avatar", options.file);
  const res = await uploadAvatar(formData);
  console.log(res.data);
  userInfo.value.imgPath = res.data;
  ElMessage.success("头像上传成功");
};

// 头像加载失败处理
const handleAvatarError = () => {
  userInfo.value.imgPath = "";
};

// 点击编辑按钮
const handleEdit = () => {
  isEditing.value = true;
  editForm.value = {
    nickname: userInfo.value.nickname,
    email: userInfo.value.email,
  };
};

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false;
  formRef.value?.resetFields();
};

// 保存个人信息
const handleSave = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      await updateUserInfo(editForm.value);
      Object.assign(userInfo.value, editForm.value);
      isEditing.value = false;
      ElMessage.success("保存成功");
    }
  });
};

// 修改密码
const handleChangePwd = async () => {
  if (!pwdFormRef.value) return;
  await pwdFormRef.value.validate(async (valid) => {
    if (valid) {
      await changePassword({
        oldPassword: pwdForm.value.oldPassword,
        newPassword: pwdForm.value.newPassword,
      });
      ElMessage.success("密码修改成功");
      resetPwdForm();
    }
  });
};

// 重置密码表单
const resetPwdForm = () => {
  pwdFormRef.value?.resetFields();
};

onMounted(() => {
  fetchUserInfo();
});
</script>

<style scoped lang="scss">
.profile-container {
  padding: 20px;
}

.profile-card {
  margin-bottom: 20px;
}

.password-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  span {
    font-size: 16px;
    font-weight: 500;
  }
}

.avatar-container {
  text-align: center;
  padding: 20px 0;
}

.avatar-actions {
  margin-top: 20px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin: 8px 0 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}

:deep(.el-form-item__content) {
  max-width: 300px;
}

.el-button + .el-button {
  margin-left: 10px;
}
</style>
